package com.link.play.fit.ai.ui.guide

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.FgGoalBinding
import com.link.play.fit.ai.ui.guide.ac.GuidePbAc
import com.link.play.fit.ai.ui.weightcontrol.ac.WeighControlPbAc
import com.link.play.fit.ai.utils.convertKgToLbs
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch


class GoalFg : BasePageFragment<FgGoalBinding>(FgGoalBinding::inflate) {

    lateinit var userGuideState: MutableStateFlow<UserGuide>

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        when (val ac = requireActivity()) {
            is GuidePbAc->{
                userGuideState = ac.viewModel.userGuideState
            }
            is WeighControlPbAc->{
                userGuideState = ac.viewModel.userGuideState
            }
        }


        lifecycleScope.launch {
            userGuideState.collectLatest {
                when (it.goal) {
                    0 -> {
                        binding.tvGainW.isSelected = true
                        binding.tvMaintain.isSelected = false
                        binding.tvLostW.isSelected = false
                    }

                    1 -> {
                        binding.tvGainW.isSelected = false
                        binding.tvMaintain.isSelected = true
                        binding.tvLostW.isSelected = false
                    }

                    2 -> {
                        binding.tvGainW.isSelected = false
                        binding.tvMaintain.isSelected = false
                        binding.tvLostW.isSelected = true
                    }
                }
            }
        }

        binding.tvGainW.setOnClickListener {
            userGuideState.update {
                val goalWeightKg = it.weightKg + 10
                Log.e(TAG, "goalWeightKg=$goalWeightKg")
                it.copy(goal = 0, goalWeightKg = goalWeightKg, goalWeightLbs = convertKgToLbs(goalWeightKg))
            }
        }
        binding.tvMaintain.setOnClickListener {
            userGuideState.update {
                it.copy(goal = 1, goalWeightKg = it.weightKg, goalWeightLbs = convertKgToLbs(it.weightLbs))
            }
        }
        binding.tvLostW.setOnClickListener {
            userGuideState.update {
                val goalWeightKg = it.weightKg - 10
                it.copy(goal = 2, goalWeightKg = goalWeightKg, goalWeightLbs = convertKgToLbs(goalWeightKg))
            }
        }
    }
}